<template>
  <el-menu :default-active="activeIndex" v-if="leftMenuData" router background-color="#04426B" text-color="white" active-text-color="white"
           unique-opened="true"
           class="el-menu-vertical-demo">
    <MenuItem router
              v-for="(item, index) in leftMenuData" :key="`${item.path}`" :item="item" :index="`${item.path}`"
    />
  </el-menu>
</template>
<script setup>
import 'element-plus/dist/index.css';
import {inject, onMounted, ref} from 'vue';
import {router,asyncRoutes} from "../router/index.ts";
import MenuItem from "@/components/MenuItem.vue";
import {AXIOS_NAME, BTN_PERMISSION_KEY} from "@/constant/constant.ts";
import {ElMessage} from "element-plus";
const $axios = inject(AXIOS_NAME);
let result = [];
let leftMenuData = ref(null);

onMounted(() => {
  $axios.post("/user/getUserMenuData").then(res => {
    const data = res.data;
    if (data.code != 1) {
      ElMessage.info("获取用户权限数据失败！");
      return;
    }
    localStorage.setItem(BTN_PERMISSION_KEY,JSON.stringify(data.data.btnData));
    buildTree(data.data.menuData, '0');
    result.forEach((item) => {
      item.path = ( item.path == null || item.path == undefined ) ? '' : item.path;
      router.addRoute('home', item);
    });
    leftMenuData.value = result;
  }).catch(error => {
    console.log(error)
  }).finally(() => {
  });
});

function buildTree(menuData, parentId, pObject) {
  for (let i = menuData.length - 1; i >= 0; i--) {
    const item = menuData[i];
    if (item.pId == parentId) {
      const {title, identification, sort, icon, component,path} = item;
      item.meta = {title, identification, sort, icon};
      item.component = getAsyncComponent(path);
      if (pObject == undefined) {
        result.push(item);
      } else {
        pObject.children = pObject.children == undefined ? [] : pObject.children;
        pObject.children.push(item);
      }
      buildTree(menuData, item.id, item);
    }
  }
}

function getAsyncComponent(path){
  if(path == null || path == undefined){
    return null;
  }
  for(const item of asyncRoutes){
    if(item.path.toLowerCase() == path.toLowerCase()){
      return item.component;
    }
  }
  return null;
}

</script>

<style>
.el-menu-item:hover{
    background-color: #409EFF;
}
</style>